package com.shaozj.common.log.interceptor;

import cn.hutool.core.date.StopWatch;
import com.shaozj.common.log.annotation.Log;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.context.annotation.Configuration;

/**
 * 切面处理操作日志
 */
@Slf4j
@Aspect
@Configuration
public class LogAspect {

    /**
     * 排除敏感属性的字段
     */
    public static final String  [] EXCLUDE_PROPERTIES = { "password"};
    private static final ThreadLocal<StopWatch> KEY_CACHE = new ThreadLocal<>();

    /**
     * 请求前执行
     * @param point 切点
     * @param controllerLog 注解
     * @throws Throwable
     */
    @Before("@annotation(controllerLog)")
    public void doBefore(JoinPoint point, Log controllerLog) throws Throwable {
        StopWatch stopWatch = new StopWatch();
        KEY_CACHE.set(stopWatch);
        stopWatch.start();
    }

    /**
     * 处理完请求后执行
     * @param joinPoint 切点
     * @param controllerLog 注解
     * @param jsonResult 结果
     */
    @AfterReturning(pointcut = "@annotation(controllerLog)", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, Log controllerLog, Object jsonResult) {
        handleLog(joinPoint, controllerLog, null, jsonResult);
    }

    /**
     * 异常处理操作
     * @param joinPoint 切点
     * @param controllerLog 注解
     * @param e 异常
     */
    @AfterThrowing(value = "@annotation(controllerLog)", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Log controllerLog, Exception e) {
        handleLog(joinPoint, controllerLog, e, null);
    }

    /**
     * 处理操作日志
     * @param joinPoint         切点
     * @param controllerLog     注解
     * @param e                 异常
     * @param jsonResult        结果
     */
    protected void handleLog(final JoinPoint joinPoint, Log controllerLog, final Exception e, Object jsonResult) {
        try {

        } catch(Exception exp) {
            // 记录本地异常日志
            log.error("异常信息:{}", exp.getMessage());
            exp.printStackTrace();
        } finally {
            KEY_CACHE.remove();
        }
    }
}
